import { PublicEventService } from './../../public-event.service';
import { Component, OnInit, ViewChild, ViewContainerRef, ComponentRef, ComponentFactoryResolver, EventEmitter } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import * as moment from 'moment';
import * as _ from 'lodash';
import { DataService } from '../../../../services/data.service';
import { Validators, FormGroup, FormControl } from '@angular/forms';
import { LayoutComponent } from "../../../global/layout/layout.component";
import { FundInfoHistoryComponent } from "../../modal/fundInfo-history/fundInfo-history.component";
import { FundInfoChangeComponent } from "../../modal/fundInfo-change/fundInfo-change.component";
import { environment } from '../../../../../environments/environment';
import { FileUploader } from "ng2-file-upload";
import { AppPaginationComponent, PaginationModel } from "../../../../widgets/pagination/pagination.component";
import * as flatpickr from 'flatpickr';
import { zh } from "flatpickr/dist/l10n/zh.js"
import { YhpService } from './yhp.service';
import { SearchComponent } from '../../modal/search/search.component';
@Component({
  selector: 'app-yhp',
  templateUrl: './yhp.component.html',
  styleUrls: ['./yhp.component.scss'],
  providers: [YhpService]
})
export class YhpComponent implements OnInit {

  // 引用模板里面定义的fundInfoHistory容器标签
  @ViewChild("fundInfoHistory", { read: ViewContainerRef })
  fundInfoHistory: ViewContainerRef;
  // 变更注册组件变量
  fundInfoHistoryComponent: ComponentRef<FundInfoHistoryComponent>;

  // 引用模板里面定义的fundInfoChange容器标签
  @ViewChild("fundInfoChange", { read: ViewContainerRef })
  fundInfoChange: ViewContainerRef;
  // 产品改造组件变量
  fundInfoChangeComponent: ComponentRef<FundInfoChangeComponent>;
  //搜索
  @ViewChild("yhpSearch", { read: ViewContainerRef })
  yhpSearch: ViewContainerRef;
  searchComponent: ComponentRef<SearchComponent>;
  // lodash
  public _: any = _;
  //接受发射的搜索条件
  public searchBody: any;
  // 当前进度
  public sStatusCode: any = 'yhp';
  // 菜单数据
  public menuData: any;
  // 菜单权限set
  public menuResourceSet: any = [];
  // 列表数据
  public listData: any = {};

  // 列表是否全选
  public isCheckedAll = false;

  // 根据产品改造单选按钮显示相应输入框的变量
  public isShowProdInput: any;

  //公募列表分页配置
  public publicListPageInfo: PaginationModel = {
    currentPageNum: 1,
    pageSize: 10,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };

  // 查询条件
  public postBody = {
    pageIndex: 1,
    pageSize: 10,
    sFundStatus: 'yhp',
    sFundCategory: '',//基金类别
    sBank: '',//托管行
    sCreator: '',//创建人
    // sPmAccount: '',
    sPmName: '',
    sFullName: '',
    sFundCode: '',
    sIsRegisterChg: ''
  };

  // 基金经理
  public managerList = [];

  constructor(
    private yhpService: YhpService,
    public router: Router,
    private route: ActivatedRoute,
    private dataService: DataService,//构造dataService
    public layoutComponent: LayoutComponent,
    private resolver: ComponentFactoryResolver,
    public publicEventService: PublicEventService
  ) {

  }

  ngOnInit() {
    let that = this;
    // 多选下拉框
    window['$'](".select2").select2();
    // 初始化日期控件
    flatpickr.localize(zh);

    // 重置查询条件
    this.postBody.sFullName = '';
    this.postBody.sFundCode = '';
    this.postBody.sIsRegisterChg = '';

    this.dataService.initTree.subscribe((data) => {
      // 权限处理
      let SessionMenuData = sessionStorage.getItem('menu');
      this.menuData = JSON.parse(SessionMenuData)
      this.menuResourceSet = [];
      _.forEach(this.menuData, (item, index) => {
        if (item.sName == '公募基金') {
          _.forEach(item.children, (it, idx) => {
            if (it.sName == '已获批') {
              that.menuResourceSet = it.resourceSet
              sessionStorage.setItem('btn-pub', this.menuResourceSet);
            }
          })
        }
      })
    })
    // 权限处理
    let SessionMenuData = sessionStorage.getItem('menu');
    this.menuData = JSON.parse(SessionMenuData)
    this.menuResourceSet = [];
    _.forEach(this.menuData, (item, index) => {
      if (item.sName == '公募基金') {
        _.forEach(item.children, (it, idx) => {
          if (it.sName == '已获批') {
            that.menuResourceSet = it.resourceSet
            sessionStorage.setItem('btn-pub', this.menuResourceSet);
          }
        })
      }
    })

    this.dataService.delay_collection = true;

    // 初始化列表checkbox
    this.isCheckedAll = false;

    // 设置当前页面
    this.publicListPageInfo.currentPageNum = 1;
    this.publicListPageInfo.pageSize = 10;
    this.loadlist();

    // 接收发射过来的数据，刷新列表数据
    this.publicEventService.eventEmit = new EventEmitter();
    this.publicEventService.eventEmit.subscribe((value: any) => {
      if (value == 'RefreshYhpList') {
        that.loadlist();
      }
    });
    // 接收产品期募集、调整费率、增设份额、其他变更后刷新列表
    this.dataService.productChangeGM = new EventEmitter();
    this.dataService.productChangeGM.subscribe((value: any) => {
      if (value) {
        that.listData = {};
        that.loadlist();
      }
    });

    //接收发射过来的数据并更新列表
    this.dataService.publicSearchEmitter = new EventEmitter();
    this.dataService.publicSearchEmitter.subscribe((value: any) => {
      if (value) {
        switch (value) {
          case 'yhp':
            that.postBody = this.dataService.publicSearchBody;

            that.loadlist();
            window['$']('#yhpSearch').modal('hide');
            break;
        }
      }
    })
  }
  // 创设新产品
  create() {
    sessionStorage.setItem('currentTitle', "创设·公募");
    this.layoutComponent.nav(null, null, "创设·公募");
    this.router.navigate(['pages/publicoffering/new/detail/add']);
  }

  // 编辑
  edit(type, item?) {
    let that = this;
    sessionStorage.setItem('parentIndex', 'yhp');
    let checkedItem = [];
    switch (type) {
      case 'dbclick':
        sessionStorage.setItem('currentTitle', "详情·已获批·公募");
        this.layoutComponent.nav(null, null, "详情·已获批·公募");
        this.router.navigate(['pages/publicoffering/fashjjlx/detail/edit/' + item.nFundNo]);
        break;
      case 'one':
        _.forEach(that.listData.list, it => {
          if (it.isChecked == true) {
            checkedItem.push(it);
          }
        })
        if (checkedItem.length == 1) {
          sessionStorage.setItem('currentTitle', "详情·已获批·公募");
          this.layoutComponent.nav(null, null, "详情·已获批·公募");
          this.router.navigate(['pages/publicoffering/fashjjlx/detail/edit/' + checkedItem[0].nFundNo]);
        } else {
          window['swal']("提示", "请选择一个产品进行查看", "warning");
        }
        break;
    }
  }

  /* 删除产品 */
  delProduct() {
    let that = this;
    let checkedItem = [];
    let checkedFundName = [];
    _.forEach(that.listData.list, item => {
      if (item.isChecked == true) {
        checkedItem.push(item.nFundNo);
        checkedFundName.push(item.sFundName);
      }
    });
    let checkedList = checkedFundName.join('、');
    if (checkedItem.length != 0) {
      window['swal']({
        type: "warning",
        showCancelButton: true,
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        closeOnConfirm: false,
        showLoaderOnConfirm: true,
        title: "提示",
        text: "<div style='max-height: 200px;overflow-y: auto;'>" + "请确认是否删除产品：" + checkedList + "</div>",
        html: true
      },
        function (isConfirm) {
          if (isConfirm) {
            var putBody = {
              "nFundNos": checkedItem
            }
            that.yhpService.del(putBody).subscribe(data => {
              if (data) {
                window['swal']("删除成功！", "", "success")
                // 重置勾选
                that.isCheckedAll = false;
                // 重新加载列表
                that.loadlist();
              }
            })
          }
        });
    }
    else {
      window['swal']("提示", "请选择一个或多个产品进行删除", "warning")
    }
  }

  // 导出
  exportExcel() {
    let that = this;
    let checkedItem = [];
    _.forEach(that.listData.list, item => {
      if (item.isChecked == true) {
        checkedItem.push(item.nFundNo);
      }
    })
    let converItem = checkedItem.join(',');
    let getBody = {
      "nFundNoList": converItem,
      "sFundStatus": this.sStatusCode,
      "sFullName": this.postBody.sFullName,
      "sFundCode": this.postBody.sFundCode,
      "sIsRegisterChg": this.postBody.sIsRegisterChg,
      "sPmName": this.postBody.sPmName,
      "sFundCategory": this.postBody.sFundCategory,
      "sBank": this.postBody.sBank,
      "sCreator": this.postBody.sCreator,
      "sPmAccount": ''

    }
    const iframe = window['$']("<iframe id='downloadiframe'>");
    iframe.attr('style', 'display:none');
    //  转码，兼容ie
    getBody.sFullName = encodeURI(getBody.sFullName)
    getBody.sFundCode = encodeURI(getBody.sFundCode)
    getBody.sPmName = encodeURI(getBody.sPmName)
    getBody.sFundCategory = encodeURI(getBody.sFundCategory)
    getBody.sBank = encodeURI(getBody.sBank)
    getBody.sCreator = encodeURI(getBody.sCreator)
    getBody.sPmAccount = encodeURI(getBody.sPmAccount)
    iframe.attr('src', environment.server + '/pms/v1/publicissue/export/publicbaseList?token=' + sessionStorage.getItem('token') +
      '&nFundNoList=' + getBody.nFundNoList +
      '&sFundStatus=' + getBody.sFundStatus +
      '&sFullName=' + getBody.sFullName +
      '&sFundCode=' + getBody.sFundCode +
      '&sIsRegisterChg=' + getBody.sIsRegisterChg +
      '&sPmName=' + getBody.sPmName +
      '&sFundCategory=' + getBody.sFundCategory +
      '&sBank=' + getBody.sBank +
      '&sCreator=' + getBody.sCreator +
      '&sPmAccount=' + getBody.sPmAccount
    );
    window['$']('body').append(iframe);
    setTimeout("$('#downloadiframe').remove()", 60000);
  }

  /**
 * 选择页码，加载指定页码列表
 * @param {pageSize}
 */
  public bondsManpageSizeChange(pageSize: number) {
    if (pageSize !== this.publicListPageInfo.pageSize) {
      this.publicListPageInfo.pageSize = pageSize;
      // this.bondsManpageInfo.currentPageNum = 1;
      this.loadlist();
    }
  }
  //公募产品管理分页
  public publicPageNavigation(currentPageNum: number) {
    this.publicListPageInfo.currentPageNum = currentPageNum;
    this.loadlist(this.publicListPageInfo.currentPageNum,
      this.publicListPageInfo.pageSize)
  }

  //查询分页列表
  loadlist(pageNum?, pageSize?) {
    let that = this;
    this.listData = {};
    this.isCheckedAll = false;
    sessionStorage.removeItem('pub_router');
    this.postBody.sFullName = _.trim(this.postBody.sFullName);
    this.postBody.sFundCode = _.trim(this.postBody.sFundCode);
    this.postBody.pageIndex = pageNum ? pageNum : this.publicListPageInfo.currentPageNum;
    this.postBody.pageSize = pageSize ? pageSize : this.publicListPageInfo.pageSize;
    this.postBody.sFundStatus = 'yhp'
    this.yhpService.list(this.postBody).subscribe(data => {
      if (data) {
        that.listData = data;
        that.publicListPageInfo.currentPageNum = data.pageNum;
        that.publicListPageInfo.totalPages = data.pages;
        that.publicListPageInfo.total = data.total; // 总记录数
        that.publicListPageInfo.startRow = data.startRow;
        that.publicListPageInfo.endRow = data.endRow;
      }
    })
  }

  //modal搜索查询分页列表
  searchlist(pageNum?, pageSize?) {
    let that = this;
    let listData = {};
    this.isCheckedAll = false;
    sessionStorage.removeItem('pub_router');
    this.postBody.pageIndex = pageNum ? pageNum : this.publicListPageInfo.currentPageNum;
    this.postBody.pageSize = pageSize ? pageSize : this.publicListPageInfo.pageSize;
    this.yhpService.list(this.searchBody).subscribe(data => {
      if (data) {
        this.listData = data;
        this.publicListPageInfo.currentPageNum = data.pageNum;
        this.publicListPageInfo.totalPages = data.pages;
        this.publicListPageInfo.total = data.total;
        this.publicListPageInfo.startRow = data.startRow;
        this.publicListPageInfo.endRow = data.endRow;
      }
    })
  }
  /**
   * 列表全选
   * @param status
   */
  checkedAll() {
    if (this.isCheckedAll) { // 更新为全选
      _.forEach(this.listData.list, item => {
        item.isChecked = true;
      });
    } else { // 更新为不全选
      _.forEach(this.listData.list, item => {
        item.isChecked = false;
      });
    }
  }
  // 列表是否全选
  ctrlCheckAll() {
    let that = this;
    let checkList = [];
    _.forEach(this.listData.list, item => {
      if (item.isChecked == true) {
        checkList.push(item);
      }
    })
    if (checkList.length == this.listData.list.length) {
      this.isCheckedAll = true;
    } else {
      this.isCheckedAll = false;
    }
  }

  // 打开 产品变更注册前的信息 modal
  showFundInfoHistoryModal(nRegisterChgNo, item) {
    window['$']("#fundInfoHistoryModal").modal('show');

    // 判断组件是否已创建，如果创建先注销
    if (this.fundInfoHistoryComponent && this.fundInfoHistoryComponent.instance) {
      this.fundInfoHistoryComponent.destroy();
    }

    // 动态创建组件的实例
    const fundInfoHistoryComponent = this.resolver.resolveComponentFactory(FundInfoHistoryComponent);
    this.fundInfoHistoryComponent = this.fundInfoHistory.createComponent(fundInfoHistoryComponent);

    // 原变更注册产品的内部编码
    this.fundInfoHistoryComponent.instance.nRegisterChgNo = item.nRegisterChgNo;
    // 产品文件内部编码
    this.fundInfoHistoryComponent.instance.nFileFundNo = item.nRegisterChgNo;
  }

  // 关闭变更注册 modal
  closeFundInfoHistroyModal() {
    window['$']("#fundInfoHistoryModal").modal('hide');
    // 注销动态创建的组件
    this.fundInfoHistoryComponent.destroy();
  }

  /**
   * 打开产品改造模态框
   * @param type 产品改造类型： bgzc-变更注册、 yqmj-延期募集、tzfl-调整费率、zsfe-增设份额、qtbg-其他变更
   */
  showFundInfoChageModal(type) {
    var that = this;
    // 产品改造类型
    this.isShowProdInput = type;
    // 勾选的产品存到数组
    var checkedObjs: any = _.concat([], _.filter(this.listData.list, { isChecked: true }));
    // 判断列表只能选择一笔数据进行产品改造
    if (checkedObjs && checkedObjs.length == 1) {
      // 已勾选的产品
      var checkedItem = checkedObjs[0];

      // 产品是否在改造审核中，如果在审核中不允许再改造
      that.yhpService.isRegistrationChange({ nFundNo: checkedItem.nFundNo, sChangeType: type }).subscribe(data => {
        if (data == true) {
          window['$']("#fundInfoChageModal").modal('show');

          // 判断组件是否已创建，如果创建先注销
          if (that.fundInfoChangeComponent && that.fundInfoChangeComponent.instance) {
            that.fundInfoChangeComponent.destroy();
          }

          // 动态创建组件的实例
          const fundInfoChangeComponent = that.resolver.resolveComponentFactory(FundInfoChangeComponent);
          that.fundInfoChangeComponent = that.fundInfoChange.createComponent(fundInfoChangeComponent);

          // 组件赋值 产品基础信息
          that.fundInfoChangeComponent.instance.fundInfoBasic = checkedItem;
          // 组件赋值 产品改造类型： bgzc-变更注册、 yqmj-延期募集、tzfl-调整费率、zsfe-增设份额、qtbg-其他变更
          that.fundInfoChangeComponent.instance.type = type;

        } else {
          window['swal']("提示", "该产品正在产品改造中", "warning");
        }
      });

    } else if (checkedObjs && checkedObjs.length > 1) {
      window['swal']("提示", "不能选择多个产品", "warning");
    } else {
      window['swal']("提示", "请选择一个产品", "warning");
    }
  }

  // 关闭产品改造模态框
  closeFundInfoChangeModal() {
    window['$']('#fundInfoChageModal').modal('hide');
    // 注销动态组件
    this.fundInfoChangeComponent.destroy();
  }

  // 基金经理
  getManagerList() {
    let that = this;
    this.yhpService.getManagerList().subscribe(data => {
      that.managerList = data;
    })
  }
  // 显示搜索modal
  showSearch() {
    if (this.searchComponent && this.searchComponent.instance) {
      this.searchComponent.destroy();
    }
    // 动态创建组件的实例
    const searchComponent = this.resolver.resolveComponentFactory(SearchComponent);
    this.searchComponent = this.yhpSearch.createComponent(searchComponent);
    this.searchComponent.instance.getBody = this.postBody;
    window['$']('#yhpSearch').modal('show');
  }
  // 点击表格头排序
  orderData(colName) {
    let listDataAsc = _.orderBy(this.listData.list, [colName], ["asc"]);
    if (JSON.stringify(this.listData.list) == JSON.stringify(listDataAsc)) {
      listDataAsc = _.orderBy(this.listData.list, [colName], ["desc"]);
    }
    this.listData.list = listDataAsc;
  }
}

